package cn.gson.CRM.controller.stock;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.CRM.model.dao.stock.StockDao;
import cn.gson.CRM.model.entity.Inout;
import cn.gson.CRM.model.entity.Product;
import cn.gson.CRM.model.mapper.InoutMapper;

@Controller
@RequestMapping("stock/stockList")
public class StockController {
	
	@Autowired
	StockDao stockDao;
	
	@Autowired
	InoutMapper inoutMapper;

	@GetMapping
	public String index(){
		return "stock/stockList";
	}
	
	@PostMapping("list")
	@ResponseBody
	public Map<String, Object> init(@RequestParam(required=false)String value,@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "10") int rows) {
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.DESC, "id"));
		Page<Product> stocks;
		
		if(value!="" && value!=null){
			stocks = stockDao.findByNameLike(pr,"%"+value+"%");
		}else{
			stocks = stockDao.findAll(pr);
		}
		Map<String, Object> data = new HashMap<>();
		data.put("rows", stocks.getContent());
		data.put("total", stocks.getTotalElements());
		return data;
	}
	
	@RequestMapping("form/{rowName}")
	@ResponseBody
	public Map<String, Object> form(@PathVariable()String rowName,int page,int rows) {

		Map<String, Object> data = new HashMap<>();
		
		PageHelper.startPage(Math.max(1, page), rows);
		List<Inout> inout = new ArrayList<>();
		inout.addAll(inoutMapper.selectIn(rowName));
		inout.addAll(inoutMapper.selectOut(rowName));
		
		PageInfo<Inout> info = new PageInfo<>(inout);
		
		data.put("rows", info.getList());
		data.put("total", info.getTotal());
		return data;
	
	}
}
